package com.xinnet.mms.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xinnet.core.utils.page.PageView;
import com.xinnet.mms.allot.service.CustomAllotConfigService;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.config.service.FlowTurnConfigService;
import com.xinnet.mms.dept.service.DeptService;
import com.xinnet.mms.entity.CustomAllotConfig;
import com.xinnet.mms.entity.CustomAllotConfigDept;
import com.xinnet.mms.entity.Dept;
import com.xinnet.mms.entity.Emp;
import com.xinnet.mms.entity.Product;
import com.xinnet.mms.entity.PublicConfig;
import com.xinnet.mms.utils.AgainPageView;
/**
 * 
 * 
 * @author 王湛智[wangzhanzhi@xinnet.com]
 *
 * @version 1.0
 *
 * @since 2014年2月14日
 *
 */
@Controller
@RequestMapping("/config")
public class ConfigController {
	@Autowired
	private CustomAllotConfigService customAllotConfigService;
	@Autowired
	private FlowTurnConfigService flowTurnConfigService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private CustomAllotService customAllotService;
	
	static Logger log=LoggerFactory.getLogger(ConfigController.class);
	/**
	 * 
	 * 功能描述：显示客户分配设置页面 部门列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月11日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/allotConfig/{pageNow}")
	public String showAllotConfigList(@PathVariable int pageNow,HttpServletRequest request,HttpServletResponse response) throws SQLException {
		Emp currentUser = (Emp)request.getSession().getAttribute("currentUser");
		String deptId = currentUser.getId();
		String deptIdStr = deptService.getChildNodeId(deptId);
		//查询部门列表
		List<Dept> deptList = deptService.getDeptListByDeptIdStr(deptIdStr);
		//request.getSession().setAttribute("deptList", deptList);
		//查询部门设置列表
		List<CustomAllotConfigDept>  customAllotConfigDeptList = customAllotConfigService.getCustomDsitributRuleByDeptIdStr(deptIdStr);
		PageView pageView = new PageView();
		AgainPageView againPageView = new AgainPageView();
		if(customAllotConfigDeptList!=null){
			pageView.setPageSize(10);
			pageView.setQueryResult(customAllotConfigDeptList.size(), customAllotConfigDeptList);
		}
		if(pageNow==1){
			againPageView.againComputePageNowRecords(pageView,1,customAllotConfigDeptList);
		}else{
			againPageView.againComputePageNowRecords(pageView,pageNow,customAllotConfigDeptList);
		}
		request.setAttribute("pageView", pageView);
		request.setAttribute("deptList", deptList);
		request.setAttribute("allotConfig", pageView.getRecords());
		return "market/config/allotconfig";
	}
	/**
	 * 
	 * 功能描述：用部门编号查询部门详细设置信息
	 *
	 * @param request
	 * @param response
	 * @param deptno
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年2月11日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/showConfig")
	public String showAllotConfig(HttpServletRequest request,HttpServletResponse response,String deptno) throws SQLException, IOException {
		List<CustomAllotConfig> allotDept=customAllotConfigService.showAllotConfigByDeptno(deptno);
		PrintWriter writer=response.getWriter();
		StringBuffer str=new StringBuffer("");
		/**拼接对象格式*/
		for(CustomAllotConfig config:allotDept) {
			str
			.append(config.getWorkDate()).append("$%")/**工作日*/
			.append(config.getStartTime()).append("$%")/**轮循开始时间*/
			.append(config.getEndTime()).append("$%")/**轮循结束时间*/
			.append(config.getPollInterval().toString()).append("&%");/**轮循间隔*/
		}
		writer.print(str.toString());
		return null;
	}

	/**
	 * 
	 * 功能描述：根据部门名称查询设置列表
	 *
	 * @param request
	 * @param response
	 * @param dname
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月11日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/search")
	public String showAllotConfigByDname(HttpServletRequest request,HttpServletResponse response,String dname) throws SQLException {
		Emp currentUser = (Emp)request.getSession().getAttribute("currentUser");
		String deptId = currentUser.getId();
		String deptIdStr = deptService.getChildNodeId(deptId);
		List<Dept> deptList = deptService.getDeptListByDeptIdStr(deptIdStr);

		List<CustomAllotConfigDept>  customAllotConfigDeptList = customAllotConfigService.getCustomDsitributRuleByDname(dname);
		PageView pageView = new PageView();
		AgainPageView againPageView = new AgainPageView();
		if(customAllotConfigDeptList!=null){
			pageView.setPageSize(10);
			pageView.setQueryResult(customAllotConfigDeptList.size(), customAllotConfigDeptList);
		}
		againPageView.againComputePageNowRecords(pageView,1,customAllotConfigDeptList);
		request.setAttribute("pageView", pageView);
		if(pageView!=null){
			request.setAttribute("allotConfig", pageView.getRecords());
		}
		request.setAttribute("deptList", deptList);
		request.setAttribute("dname", dname);
		return "market/config/allotconfig";
	}
	
	/**
	 * 
	 * 功能描述：客户分配批量设置
	 *
	 * @param requets
	 * @param response
	 * @param deptnos
	 * @param dates
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年2月12日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/configBatch")
	public String configBatch(HttpServletRequest requets,HttpServletResponse response,String deptnos,String dates) throws SQLException, IOException {
		/**批量设置调用*/
		customAllotConfigService.updateAllotConfigBatch(deptnos, dates);
		
		PrintWriter writer=response.getWriter();
		writer.print(1);
		return null;
	}
	/**
	 * 
	 * 功能描述：客户分配批量设置
	 *
	 * @param requets
	 * @param response
	 * @param deptno
	 * @param startTime
	 * @param endTime
	 * @param poll
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年2月12日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/configAlong")
	public String configAlong(HttpServletRequest requets,HttpServletResponse response,String deptno,String startTime,String endTime,String poll,String workDate) throws SQLException, IOException {
		/**调用更新设置*/
		customAllotConfigService.updateAllotConfigAlong(deptno,startTime,endTime,poll,workDate);
		
		PrintWriter writer=response.getWriter();
		writer.print(1);
		return null;
	}
	/**
	 * 
	 * 功能描述：显示流转设置列表
	 *
	 * @param requets
	 * @param response
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月13日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/flowConfig")
	public String showflowConfigList(HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException {
		List<Product> list=flowTurnConfigService.getProductConfig();
		request.setAttribute("publicCycle", flowTurnConfigService.getMiddleServiceCycleInCheck());
		request.setAttribute("publicPerf", flowTurnConfigService.getPerfDayInCheck());
		request.setAttribute("publicPriority", flowTurnConfigService.getPriorityInCheck());
		request.setAttribute("publicWarning", flowTurnConfigService.getWarningTime());
		request.setAttribute("publicRemind", flowTurnConfigService.getPublicRemind());
		request.setAttribute("pollInterval", customAllotService.getPollInterval().getPollInterval());
		request.setAttribute("productConfigList", list);
		return "market/config/flowconfig";
	}
	/**
	 * 
	 * 功能描述：设置修改到期预警时间
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年3月13日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/setWarningTime")
	public String setWarningTime(HttpServletRequest request,HttpServletResponse response,String time) throws SQLException, IOException {
		int dueTime=0;
		try {
			dueTime=Integer.parseInt(time);
		} catch(Exception e) {
			log.debug(request.getRemoteAddr()+" 试图xss攻击");
			return null;
		}
		flowTurnConfigService.updateWarningTime(dueTime);
		
		PrintWriter writer=response.getWriter();
		writer.print(1);
		return null;
	}
	/**
	 * 
	 * 功能描述：设置即将流走客户提醒时间
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年3月13日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/setRemind")
	public String setRemind(HttpServletRequest request,HttpServletResponse response,String remind) throws SQLException, IOException {
		int warningTime=0;
		try {
			warningTime=Integer.parseInt(remind);
		} catch(Exception e) {
			log.debug(request.getRemoteAddr()+" 试图xss攻击");
			return null;
		}
		flowTurnConfigService.updatePublicRemind(warningTime);
		
		PrintWriter writer=response.getWriter();
		writer.print(1);
		return null;
	}
	
	/**
	 * 
	 * 功能描述：设置即将流走客户提醒时间
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 *
	 * @author 王志军[wangzhijun@xinnet.com]
	 *
	 * @since 2015年11月16日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/setPollInterval")
	public String setPollInterval(HttpServletRequest request,HttpServletResponse response,String pollInterval) throws SQLException, IOException {
		int pollIntervalInt = 0;
		try {
			pollIntervalInt=Integer.parseInt(pollInterval);
		} catch(Exception e) {
			log.debug(request.getRemoteAddr()+" 试图xss攻击,传入的String类型参数为：" + pollInterval);
			return null;
		}
		customAllotService.updatePollInterval(pollIntervalInt);
		
		PrintWriter writer=response.getWriter();
		writer.print(1);
		return null;
	}
	/**
	 * 
	 * 功能描述：设置流转规则
	 *
	 * @param request
	 * @param response
	 * @param ids
	 * @param sysallocationNodealholdtimem
	 * @param pushNodealholdtime
	 * @param startServiceCycle
	 * @param endServiceCycle
	 * @param goOpenseaTime
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月14日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/setFlowConfig")
	public String updateflowConfig(HttpServletRequest request,HttpServletResponse response,
			String ids,
			String sysallocationNodealholdtime,
			String pushNodealholdtime,
			String redevNodealholdtime,
			String startServiceCycle,
			String endServiceCycle,
			String goOpenseaTime) throws SQLException, IOException {
		
		flowTurnConfigService.updateFlowConfig(ids, sysallocationNodealholdtime, pushNodealholdtime, redevNodealholdtime, startServiceCycle, endServiceCycle, goOpenseaTime);
		PrintWriter writer=response.getWriter();
		writer.print(1);
		return null;
	}
	/**
	 * 
	 * 功能描述：修改所有产品线的二次开发停顿期 加入审核
	 *
	 * @param request
	 * @param response
	 * @param middleServiceCycle
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月14日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/setMiddleServiceCycleAddCheck")
	public String updateMiddleServiceCycleAddCheck(HttpServletRequest request,HttpServletResponse response,String middleServiceCycle) throws SQLException, IOException {
		
		flowTurnConfigService.updateMiddleServiceCycleAddCheck(Integer.parseInt(middleServiceCycle));
		/**打印成功命令 前台ajax接收指令*/
		PrintWriter writer=response.getWriter();
		writer.print(1);
		return null;
	}
	/**
	 * 
	 * 功能描述：修改业绩保留期 加入审核
	 *
	 * @param request
	 * @param response
	 * @param day
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月14日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/setPerfDayInCheck")
	public String updatePerfAddCheck(HttpServletRequest request,HttpServletResponse response,String day) throws SQLException, IOException {
		
		flowTurnConfigService.updatePerfDayInCheck(Integer.parseInt(day));
		
		PrintWriter writer=response.getWriter();
		writer.print(1);
		return null;
	}
	/**
	 * 
	 * 功能描述：取得产品优先级列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月14日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/getPriority")
	public String getProductPriority(HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException {
		
		List<Product> PriorityList=flowTurnConfigService.getProductPriority();
		StringBuffer str=new StringBuffer("");
		for(Product product:PriorityList) {
			str
			.append(product.getId()).append(":")
			.append(product.getProductName()).append(":")
			.append(product.getPriority()).append("$#");
		}
		PrintWriter writer=response.getWriter();
		writer.print(str.toString());
		return null;
	}
	/**
	 * 
	 * 功能描述：确认修改优先级列表
	 *
	 * @param request
	 * @param response
	 * @param config
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月14日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/setPriority")
	public String setProductPriority(HttpServletRequest request,HttpServletResponse response,String config) throws SQLException, IOException {
		String[] configs=config.split(":");
		
		for(int i=0;i<configs.length;i++) {
			System.out.println(i+":"+(i+1));
			flowTurnConfigService.updatePriority(configs[i],(i+1));
		}
		flowTurnConfigService.updatePriorityAddCheck();
		PrintWriter writer=response.getWriter();
		writer.print(1);
		return null;
	}
	/**
	 * 
	 * 功能描述：打开分配优先级显示页面
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年3月24日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/allotPriority")
	public String showAllotPriority(HttpServletRequest request,HttpServletResponse response) throws SQLException {
		return "market/config/allotpriority";
	}
	/**
	 * 
	 * 功能描述：加载分配优先级产品列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年3月24日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/loadAllotPriority")
	public String loadAllotPriority(HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException {
		List<Product> PriorityList=flowTurnConfigService.getAllotPriority();
		PublicConfig config=flowTurnConfigService.getDefaultProduct();
		StringBuffer str=new StringBuffer("");
		for(Product product:PriorityList) {
			str
			.append(product.getId()).append(":")
			.append(product.getProductName()).append(":")
			.append(product.getAllotPriority()).append("$#");
		}
		/**拼接默认产品*/
		str.append("||");
		str.append(config.getConfigValue());
		
		PrintWriter writer=response.getWriter();
		writer.print(str.toString());
		return null;
	}
	/**
	 * 
	 * 功能描述：修改分配优先级
	 *
	 * @param request
	 * @param response
	 * @param config
	 * @param pid
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年3月24日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/setAllotPriority")
	public String setAllotProductPriority(HttpServletRequest request,HttpServletResponse response,String config,String defaultProduct) throws SQLException, IOException {
		String[] configs=config.split(":");
		
		for(int i=0;i<configs.length;i++) {
			flowTurnConfigService.updateAllotPriority(configs[i],(i+1));
		}
		flowTurnConfigService.updateDefaultProduct(defaultProduct);
		
		PrintWriter writer=response.getWriter();
		writer.print(1);
		return null;
	}
	public CustomAllotService getCustomAllotService() {
		return customAllotService;
	}
	public void setCustomAllotService(CustomAllotService customAllotService) {
		this.customAllotService = customAllotService;
	}
}
